//
//  PostDetailViewController.m
//  iWeddingDirectory
//
//  Created by Tung Ngo on 6/28/12.
//  Copyright (c) 2012 Home. All rights reserved.
//

#import "PostDetailViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "API.h"
#import "DatabaseManager.h"

@implementation PostDetailViewController

@synthesize post;
@synthesize postType;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
    
    self.title = @"Post";
    
//    imageViewThumbnail = [[UIImageView alloc] initWithFrame:CGRectMake(20, 10, 280, 210)];
//    [imageViewThumbnail.layer setBorderWidth:1.0f];
//    [imageViewThumbnail.layer setBorderColor:[UIColor blackColor].CGColor];
//    [imageViewThumbnail.layer setCornerRadius:3.0f];
//    [imageViewThumbnail setContentMode:UIViewContentModeScaleAspectFit];
//    [self.view addSubview:imageViewThumbnail];
//    labelTitle = [[UILabel alloc] initWithFrame:CGRectMake(20, 224, 280, 36)];
//    [labelTitle setTextAlignment:UITextAlignmentLeft];
//    [self.view addSubview:labelTitle];
//    textViewContent = [[UITextView alloc] initWithFrame:CGRectMake(20, 260, 280, 102)];
//    [textViewContent setEditable:NO];
//    [self.view addSubview:textViewContent];
    
    if (postType == REMOTE_POST) {
        UIActivityIndicatorView *waitingIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [waitingIndicator setTag:1000];
        [waitingIndicator setCenter:CGPointMake(160, 181)];
        [self.view addSubview:waitingIndicator];
        [waitingIndicator startAnimating];
        [waitingIndicator release];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPostReceived:) name:kPostReceivedNotification object:nil];
        API *api = [API sharedInstance];
        [api getPostWithId:post.postId];
    }
    else {
//        labelTitle.text = post.title;
//        textViewContent.text = post.content;
//        [self performSelector:@selector(loadThumbnail) withObject:nil afterDelay:0.05];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
    int section = indexPath.section;
    if (section == 1) {
        cell.textLabel.text = post.description;
    }
    else if (section == 2) {
        cell.textLabel.text = post.phone;
    }
    else if (section == 3) {
        cell.textLabel.text = post.phone;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark - Post received notification

- (void)onPostReceived:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kPostReceivedNotification object:nil];
    
    UIActivityIndicatorView *waitingIndicator = (UIActivityIndicatorView *)[self.view viewWithTag:1000];
    [waitingIndicator stopAnimating];
    
    NSDictionary *result = [notification userInfo];
//    NSString *title = [[result objectForKey:@"post"] objectForKey:@"title"];
//    NSString *content = [[result objectForKey:@"post"] objectForKey:@"content"];
//    NSString *thumbnail = [[result objectForKey:@"post"] objectForKey:@"image"];
    //NSString *title = [[result objectForKey:@"business_info"] objectForKey:@"title"];
    NSString *content = [[result objectForKey:@"business_info"] objectForKey:@"description"];
    NSString *thumbnail = [[result objectForKey:@"business_info"] objectForKey:@"display_image"];
    post.title = @"";//title;
    post.content = content;
    
    if (thumbnail != nil && ![thumbnail isEqual:[NSNull null]]) {
        post.thumbnail = thumbnail;
    }
    
    DatabaseManager *databaseManager = [DatabaseManager sharedInstance];
    if (![databaseManager isPostExisted:post.postId]) {
        //NSLog(@"Go here");
        UIButton *buttonAddToFavourite = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [buttonAddToFavourite setFrame:CGRectMake(150, 330, 150, 30)];
        [buttonAddToFavourite setTitle:@"Add to Favourite" forState:UIControlStateNormal];
        [buttonAddToFavourite addTarget:self action:@selector(onButtonAddToFavouriteClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:buttonAddToFavourite];
        //[buttonAddToFavourite setEnabled:NO];
    }
}

#pragma mark - Button click handlers

- (void)onButtonAddToFavouriteClicked:(id)sender
{
    DatabaseManager *databaseManager = [DatabaseManager sharedInstance];
    [databaseManager addPost:post];
    UIButton *buttonAddToFavourite = (UIButton *)sender;
    [buttonAddToFavourite setEnabled:NO];
    //[buttonAddToFavourite setHidden:YES];
    buttonAddToFavourite.alpha = 0.0;
    buttonAddToFavourite.opaque = YES;
    [buttonAddToFavourite removeFromSuperview];
   
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kPostAddedToFavouritesNotification object:nil userInfo:[NSDictionary dictionaryWithObject:post forKey:@"new post"]];
}

@end
